<template>
  <div class="resource-detail">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 资源详情内容 -->
    <div v-else-if="resource" class="detail-container">
      <!-- 资源头部信息 -->
      <div class="resource-header">
        <div class="resource-main-info">
          <div class="file-preview">
            <div class="file-icon" :class="getFileIconClass(resource.fileType)">
              <span class="file-icon-emoji">{{ getFileIcon(resource.fileType) }}</span>
            </div>
            <div class="file-type-badge">{{ resource.fileType?.toUpperCase() }}</div>
          </div>
          
          <div class="resource-info">
            <h1 class="resource-title">{{ resource.title }}</h1>
            <div class="resource-meta">
              <div class="meta-row">
                <el-tag :type="getCategoryTagType(resource.categoryName)" size="default">
                  {{ resource.categoryName }}
                </el-tag>
                <span class="file-size">{{ formatFileSize(resource.fileSize) }}</span>
                <span class="upload-date">{{ formatDate(resource.uploadTime) }}</span>
              </div>
              <div class="meta-row">
                <div class="uploader-info">
                  <el-avatar :size="24" class="uploader-avatar">
                    <template #default>
                      <span style="font-size: 14px;">👤</span>
                    </template>
                  </el-avatar>
                  <span class="uploader-name">{{ resource.uploaderName }}</span>
                </div>
                <div class="resource-stats">
                  <span class="stat-item">
                    <i class="el-icon-view"></i>
                    {{ resource.viewCount || 0 }} 浏览
                  </span>
                  <span class="stat-item">
                    <i class="el-icon-download"></i>
                    {{ resource.downloadCount || 0 }} 下载
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="resource-actions">
          <el-button type="primary" size="large" @click="downloadResource" :loading="downloading">
            <i class="el-icon-download"></i>
            立即下载
          </el-button>
          <el-button @click="toggleFavorite" :loading="favoriteLoading">
            <i :class="isFavorited ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
            {{ isFavorited ? '已收藏' : '收藏' }}
          </el-button>
          <el-button @click="showRatingDialog = true">
            <i class="el-icon-star-off"></i>
            评价
          </el-button>
        </div>
      </div>

      <!-- 资源描述 -->
      <div class="resource-description">
        <h3>资源描述</h3>
        <div class="description-content">
          {{ resource.description || '暂无描述' }}
        </div>
      </div>

      <!-- 评分和评价区域 -->
      <div class="rating-section">
        <div class="rating-summary">
          <h3>用户评价</h3>
          <div class="rating-overview">
            <div class="average-rating">
              <div class="rating-score">{{ averageRating.toFixed(1) }}</div>
              <el-rate
                v-model="averageRating"
                disabled
                show-text
                text-color="#ff9900"
                class="rating-stars"
              />
              <div class="rating-count">{{ totalRatings }} 人评价</div>
            </div>
            <div class="rating-distribution">
              <div v-for="(count, index) in reversedRatingDistribution" :key="index" class="rating-bar">
                <span class="star-label">{{ 5 - index }}星</span>
                <div class="bar-container">
                  <div class="bar-fill" :style="{ width: getRatingPercentage(count) + '%' }"></div>
                </div>
                <span class="bar-count">{{ count }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户评分 -->
        <div v-if="isLoggedIn" class="user-rating">
          <h4>给这个资源评分</h4>
          <div class="rating-input">
            <el-rate
              v-model="userRating"
              show-text
              text-color="#ff9900"
              @change="submitRating"
              :texts="['极差', '失望', '一般', '满意', '惊喜']"
            />
            <span v-if="userRating > 0" class="rating-text">{{ getRatingText(userRating) }}</span>
          </div>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <div class="comments-header">
          <h3>用户评论 ({{ comments.length }})</h3>
          <el-button v-if="isLoggedIn" type="primary" @click="showCommentDialog = true">
            写评论
          </el-button>
        </div>

        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :size="40">
                <template #default>
                  <span style="font-size: 20px;">👤</span>
                </template>
              </el-avatar>
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.username }}</span>
                <el-rate
                  v-if="comment.rating"
                  :value="comment.rating"
                  disabled
                  size="small"
                  class="comment-rating"
                />
                <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>

            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="comments.length === 0" class="empty-comments">
            <i class="el-icon-chat-dot-round"></i>
            <p>暂无评论，快来发表第一个评论吧！</p>
          </div>
        </div>
      </div>

      <!-- 相关推荐 -->
      <div class="related-resources">
        <h3>相关推荐</h3>
        <div class="related-grid">
          <div 
            v-for="item in relatedResources" 
            :key="item.resourceId"
            class="related-item"
            @click="goToResource(item.resourceId)"
          >
            <div class="related-icon">
              <span class="file-icon-emoji">{{ getFileIcon(item.fileType) }}</span>
            </div>
            <div class="related-info">
              <h4 class="related-title">{{ item.title }}</h4>
              <div class="related-meta">
                <span class="related-uploader">{{ item.uploaderName }}</span>
                <span class="related-downloads">{{ item.downloadCount }} 下载</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 资源不存在 -->
    <div v-else class="resource-not-found">
      <div class="not-found-icon">
        <i class="el-icon-document-delete"></i>
      </div>
      <h3>资源不存在</h3>
      <p>您查找的资源可能已被删除或不存在</p>
      <el-button type="primary" @click="$router.push('/resources')">
        返回资源列表
      </el-button>
    </div>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="showRatingDialog"
      title="评价资源"
      width="500px"
      @close="resetRatingForm"
    >
      <div class="rating-dialog-content">
        <div class="resource-info-mini">
          <div class="mini-icon">
            <span class="file-icon-emoji">{{ getFileIcon(resource.fileType) }}</span>
          </div>
          <div class="mini-details">
            <h4>{{ resource.title }}</h4>
            <p>{{ resource.categoryName }} · {{ resource.uploaderName }}</p>
          </div>
        </div>
        
        <el-form :model="ratingForm" :rules="ratingRules" ref="ratingFormRef" label-width="80px">
          <el-form-item label="评分" prop="rating" required>
            <div class="rating-input-section">
              <el-rate
                v-model="ratingForm.rating"
                show-text
                text-color="#ff9900"
                :texts="['极差', '失望', '一般', '满意', '惊喜']"
                size="large"
              />
              <span v-if="ratingForm.rating > 0" class="rating-text">
                {{ getRatingText(ratingForm.rating) }}
              </span>
            </div>
          </el-form-item>
          
          <el-form-item label="评论" prop="comment">
            <el-input
              v-model="ratingForm.comment"
              type="textarea"
              :rows="4"
              placeholder="分享您对这个资源的看法..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="showRatingDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRatingAndComment" :loading="ratingSubmitting">
          提交评价
        </el-button>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog
      v-model="showCommentDialog"
      title="发表评论"
      width="500px"
      @close="resetCommentForm"
    >
      <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="分享您对这个资源的看法..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment" :loading="commentSubmitting">
          发表评论
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import favoriteApi from '@/api/favorite'
import ratingApi from '@/api/rating'
import commentApi from '@/api/comment'

export default {
  name: 'ResourceDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    
    // 响应式数据
    const loading = ref(true)
    const resource = ref(null)
    const downloading = ref(false)
    const favoriteLoading = ref(false)
    const isFavorited = ref(false)
    const comments = ref([])
    const relatedResources = ref([])
    const showCommentDialog = ref(false)
    const showRatingDialog = ref(false)
    const commentSubmitting = ref(false)
    const ratingSubmitting = ref(false)
    const commentFormRef = ref()
    const ratingFormRef = ref()
    
    // 评分相关
    const userRating = ref(0)
    const averageRating = ref(0)
    const totalRatings = ref(0)
    const ratingDistribution = ref([0, 0, 0, 0, 0])
    
    // 评论表单
    const commentForm = reactive({
      content: '',
      rating: 0
    })
    
    // 评价表单
    const ratingForm = reactive({
      rating: 0,
      comment: ''
    })
    
    const commentRules = {
      content: [
        { required: true, message: '请输入评论内容', trigger: 'blur' },
        { min: 5, max: 500, message: '评论内容长度在 5 到 500 个字符', trigger: 'blur' }
      ],
      rating: [
        { type: 'number', min: 0, max: 5, message: '评分必须在0-5星之间', trigger: 'change' }
      ]
    }
    
    const ratingRules = {
      rating: [
        { required: true, message: '请选择评分', trigger: 'change' },
        { type: 'number', min: 1, max: 5, message: '评分必须在1-5星之间', trigger: 'change' }
      ]
    }
    
    // 计算属性
    const isLoggedIn = computed(() => store.getters.getLoginStatus)
    const resourceId = computed(() => route.params.id)
    
    // 倒序显示评分分布（5星在上，1星在下）
    const reversedRatingDistribution = computed(() => {
      // 确保ratingDistribution.value是数组，且不为null/undefined
      if (Array.isArray(ratingDistribution.value)) {
        return [...ratingDistribution.value].reverse()
      }
      return [0, 0, 0, 0, 0]
    })
    
    // 方法
    const loadResourceDetail = async () => {
      try {
        loading.value = true
        const response = await request.get(`resources/${resourceId.value}`)
        resource.value = response.data
        
        // 增加浏览量
        await incrementViewCount()
        
        // 加载相关数据
        await Promise.all([
          loadRatingData(),
          loadComments(),
          loadRelatedResources(),
          checkIfFavorited()
        ])
      } catch (error) {
        console.error('加载资源详情失败:', error)
        ElMessage.error('加载资源详情失败')
        // 使用模拟数据
        resource.value = generateMockResource()
        await loadMockData()
      } finally {
        loading.value = false
      }
    }
    
    const generateMockResource = () => {
      return {
        resourceId: resourceId.value,
        title: 'Vue.js 完整开发指南',
        description: '这是一个全面的Vue.js开发指南，包含了从基础到高级的所有知识点。内容涵盖了Vue.js 3.0的新特性、组合式API、响应式原理、组件开发、状态管理、路由管理等核心概念。适合初学者入门和有经验的开发者进阶学习。',
        categoryName: '编程开发',
        uploaderName: '张老师',
        fileType: 'pdf',
        fileSize: 15728640, // 15MB
        downloadCount: 1520,
        viewCount: 3240,
        uploadTime: '2024-01-15T10:30:00Z'
      }
    }
    
    const loadMockData = async () => {
      // 模拟评分数据
      averageRating.value = 4.3
      totalRatings.value = 89
      ratingDistribution.value = [2, 5, 15, 38, 29]
      userRating.value = 0
      
      // 模拟评论数据
      comments.value = [
        {
          id: 1,
          username: '学习达人',
          content: '非常好的资源，内容详细，讲解清晰，对Vue.js的学习很有帮助！',
          rating: 5,
          createdAt: '2024-01-20T14:30:00Z',
          likeCount: 12,
          isLiked: false
        },
        {
          id: 2,
          username: '前端小白',
          content: '作为初学者，这个资源让我快速理解了Vue.js的核心概念，推荐！',
          rating: 4,
          createdAt: '2024-01-19T16:45:00Z',
          likeCount: 8,
          isLiked: false
        }
      ]
      
      // 模拟相关资源
      relatedResources.value = [
        {
          resourceId: 2,
          title: 'React 开发实战教程',
          uploaderName: '李老师',
          downloadCount: 980,
          fileType: 'pdf'
        },
        {
          resourceId: 4,
          title: 'JavaScript 高级编程',
          uploaderName: '王老师',
          downloadCount: 756,
          fileType: 'pdf'
        },
        {
          resourceId: 5,
          title: 'CSS3 动画详解',
          uploaderName: '赵老师',
          downloadCount: 423,
          fileType: 'doc'
        }
      ]
    }
    
    const incrementViewCount = async () => {
      try {
        await request.post(`resources/${resourceId.value}/view`)
      } catch (error) {
        console.error('增加浏览量失败:', error)
      }
    }
    
    const loadRatingData = async () => {
      try {
        const response = await ratingApi.getRatingStats(resourceId.value)
        if (response.success) {
          const stats = response.data
          averageRating.value = stats.averageRating || 0
          totalRatings.value = stats.totalRatings || 0
          
          // 确保distribution是数组格式
          if (Array.isArray(stats.distribution)) {
            ratingDistribution.value = stats.distribution
          } else if (stats.distribution && typeof stats.distribution === 'object') {
            // 如果后端返回的是对象格式，转换为数组
            const distArray = [0, 0, 0, 0, 0]
            for (let i = 1; i <= 5; i++) {
              if (stats.distribution[i] !== undefined) {
                distArray[i - 1] = stats.distribution[i]
              }
            }
            ratingDistribution.value = distArray
          } else {
            ratingDistribution.value = [0, 0, 0, 0, 0]
          }
        } else {
          // API返回失败时使用默认值
          averageRating.value = 0
          totalRatings.value = 0
          ratingDistribution.value = [0, 0, 0, 0, 0]
        }
        
        // 获取用户评分
        if (isLoggedIn.value) {
          const userRatingResponse = await ratingApi.getUserRating(resourceId.value)
          if (userRatingResponse.success) {
            // 后端返回的是对象格式 {rating: x, comment: ""}，需要提取rating值
            const userData = userRatingResponse.data
            if (userData && typeof userData === 'object') {
              userRating.value = userData.rating || 0
            } else {
              userRating.value = userData || 0
            }
          } else {
            userRating.value = 0
          }
        } else {
          userRating.value = 0
        }
      } catch (error) {
        console.error('加载评分数据失败:', error)
        averageRating.value = 0
        totalRatings.value = 0
        ratingDistribution.value = [0, 0, 0, 0, 0]
        userRating.value = 0
      }
    }
    
    const loadComments = async () => {
      try {
        const response = await commentApi.getResourceComments(resourceId.value, { page: 1, size: 50 })
        if (response.success) {
          comments.value = response.data.records || []
        } else {
          comments.value = []
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        comments.value = []
      }
    }
    
    const loadRelatedResources = async () => {
      try {
        const response = await request.get(`resources/${resourceId.value}/related`)
        relatedResources.value = response.data || []
      } catch (error) {
        console.error('加载相关资源失败:', error)
        // 使用模拟数据
        relatedResources.value = [
          {
            resourceId: 2,
            title: 'React 开发实战教程',
            uploaderName: '李老师',
            downloadCount: 980,
            fileType: 'pdf'
          },
          {
            resourceId: 4,
            title: 'JavaScript 高级编程',
            uploaderName: '王老师',
            downloadCount: 756,
            fileType: 'pdf'
          }
        ]
      }
    }
    
    const checkIfFavorited = async () => {
      if (!isLoggedIn.value) return
      
      try {
        const response = await favoriteApi.checkFavoriteStatus(resourceId.value)
        if (response.success) {
          isFavorited.value = response.data
        } else {
          isFavorited.value = false
        }
      } catch (error) {
        console.error('检查收藏状态失败:', error)
        isFavorited.value = false
      }
    }
    
    const downloadResource = async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录后再下载')
        return
      }
      
      try {
        downloading.value = true
        
        // 模拟下载
        const response = await request.get(`resources/${resourceId.value}/download`, {
          responseType: 'blob'
        })
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${resource.value.title}.${resource.value.fileType}`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(url)
        
        // 更新下载计数
        resource.value.downloadCount++
        ElMessage.success('下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        ElMessage.error('下载失败，请稍后重试')
      } finally {
        downloading.value = false
      }
    }
    
    const toggleFavorite = async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }
      
      try {
        favoriteLoading.value = true
        
        if (isFavorited.value) {
          // 取消收藏
          await favoriteApi.removeFavorite(resource.value.resourceId)
          isFavorited.value = false
          ElMessage.success('取消收藏成功')
        } else {
          // 添加收藏
          await favoriteApi.addFavorite(resource.value.resourceId)
          isFavorited.value = true
          ElMessage.success('收藏成功')
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        ElMessage.error(error.message || '操作失败，请稍后重试')
      } finally {
        favoriteLoading.value = false
      }
    }
    
    const submitRating = async (rating) => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
      }
      
      try {
        const response = await ratingApi.rateResource(resourceId.value, rating)
        if (response.success) {
          ElMessage.success('评分成功')
          await loadRatingData()
          
          // 通知资源列表页面需要刷新
          localStorage.setItem('resourceListNeedsRefresh', 'true')
          localStorage.setItem('lastRatingUpdate', Date.now().toString())
        } else {
          ElMessage.error(response.message || '评分失败')
        }
      } catch (error) {
        console.error('评分失败:', error)
        ElMessage.error('评分失败，请稍后重试')
      }
    }
    
    const submitComment = async () => {
      if (!commentFormRef.value) {
                  // 评论表单引用不存在
        return
      }
      
      try {
        // 表单验证
        await commentFormRef.value.validate()
        commentSubmitting.value = true
        
        // 准备评论数据
        const commentData = {
          content: commentForm.content.trim(),
          rating: commentForm.rating > 0 ? commentForm.rating : null
        }
        
        // 提交评论数据日志已移除
        
        const response = await commentApi.addComment(resourceId.value, commentData)
                  // 评论提交响应日志已移除
        
        if (response.success || response.code === 200) {
          ElMessage.success('评论发表成功')
          showCommentDialog.value = false
          resetCommentForm()
          await loadComments()
          
          // 如果有评分，刷新评分数据
          if (commentForm.rating > 0) {
            await loadRatingData()
          }
        } else {
                      // 评论提交失败日志已移除
          ElMessage.error(response.message || '评论发表失败')
        }
      } catch (error) {
        console.error('发表评论失败:', error)
        if (error.response) {
          console.error('错误响应:', error.response.data)
          ElMessage.error(`评论发表失败: ${error.response.data.message || error.message}`)
        } else {
          ElMessage.error('发表评论失败，请稍后重试')
        }
      } finally {
        commentSubmitting.value = false
      }
    }
    
    const resetCommentForm = () => {
      commentForm.content = ''
      commentForm.rating = 0
      if (commentFormRef.value) {
        commentFormRef.value.resetFields()
      }
    }
    
    const goToResource = (resourceId) => {
      if (resourceId && resourceId !== route.params.id) {
        router.push(`/resources/${resourceId}`)
        // 重新加载页面数据
        nextTick(() => {
          loadResourceDetail()
        })
      }
    }
    
    // 工具方法
    const getFileIcon = (fileType) => {
      if (!fileType) return '📄'
      const type = fileType.toLowerCase()
      if (['pdf'].includes(type)) return '📄'
      if (['doc', 'docx'].includes(type)) return '📝'
      if (['ppt', 'pptx'].includes(type)) return '📊'
      if (['mp4', 'avi', 'mkv'].includes(type)) return '🎬'
      if (['mp3', 'wav'].includes(type)) return '🎵'
      if (['jpg', 'jpeg', 'png', 'gif'].includes(type)) return '🖼️'
      if (['zip', 'rar', '7z'].includes(type)) return '📦'
      return '📄'
    }
    
    const getFileIconClass = (fileType) => {
      if (!fileType) return 'file-icon-default'
      const type = fileType.toLowerCase()
      if (['pdf'].includes(type)) return 'file-icon-pdf'
      if (['doc', 'docx'].includes(type)) return 'file-icon-word'
      if (['ppt', 'pptx'].includes(type)) return 'file-icon-ppt'
      if (['mp4', 'avi', 'mkv'].includes(type)) return 'file-icon-video'
      if (['mp3', 'wav'].includes(type)) return 'file-icon-audio'
      if (['jpg', 'jpeg', 'png', 'gif'].includes(type)) return 'file-icon-image'
      return 'file-icon-default'
    }
    
    const getCategoryTagType = (category) => {
      const typeMap = {
        '编程开发': 'primary',
        '设计创意': 'success',
        '数据科学': 'warning',
        '产品运营': 'info',
        '语言学习': 'danger'
      }
      return typeMap[category] || 'primary'
    }
    
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    const getRatingPercentage = (count) => {
      return totalRatings.value > 0 ? (count / totalRatings.value) * 100 : 0
    }
    
    const getRatingText = (rating) => {
      const texts = ['', '极差', '失望', '一般', '满意', '惊喜']
      return texts[rating] || ''
    }
    
    // 评价相关方法
    const submitRatingAndComment = async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录后再评价')
        return
      }
      
      if (!ratingFormRef.value) return
      
      try {
        await ratingFormRef.value.validate()
        ratingSubmitting.value = true
        
        // 提交评分
        if (ratingForm.rating > 0) {
          const ratingResponse = await ratingApi.rateResource(resourceId.value, ratingForm.rating)
          if (!ratingResponse.success) {
            ElMessage.error(ratingResponse.message || '评分失败')
            return
          }
        }
        
        // 提交评论（如果有内容）
        if (ratingForm.comment.trim()) {
          const commentResponse = await commentApi.addComment(resourceId.value, {
            content: ratingForm.comment.trim(),
            rating: ratingForm.rating
          })
          if (!commentResponse.success) {
            ElMessage.error(commentResponse.message || '评论发表失败')
            return
          }
        }
        
        ElMessage.success('评价提交成功')
        showRatingDialog.value = false
        resetRatingForm()
        
        // 刷新数据
        await Promise.all([
          loadRatingData(),
          loadComments()
        ])
        
        // 通知资源列表页面需要刷新
        localStorage.setItem('resourceListNeedsRefresh', 'true')
        localStorage.setItem('lastRatingUpdate', Date.now().toString())
      } catch (error) {
        console.error('提交评价失败:', error)
        ElMessage.error('提交评价失败，请稍后重试')
      } finally {
        ratingSubmitting.value = false
      }
    }
    
    const resetRatingForm = () => {
      ratingForm.rating = 0
      ratingForm.comment = ''
      if (ratingFormRef.value) {
        ratingFormRef.value.resetFields()
      }
    }
    
    // 生命周期
    onMounted(async () => {
      // 延迟执行以确保DOM完全准备好
      await new Promise(resolve => setTimeout(resolve, 100))
      
      try {
        store.dispatch('setPageTitle', '资源详情')
        await loadResourceDetail()
      } catch (error) {
        console.error('初始化数据加载失败:', error)
      }
    })
    
    return {
      // 响应式数据
      loading,
      resource,
      downloading,
      favoriteLoading,
      isFavorited,
      comments,
      relatedResources,
      showCommentDialog,
      showRatingDialog,
      commentSubmitting,
      ratingSubmitting,
      commentFormRef,
      ratingFormRef,
      userRating,
      averageRating,
      totalRatings,
      ratingDistribution,
      commentForm,
      ratingForm,
      commentRules,
      ratingRules,
      
      // 计算属性
      isLoggedIn,
      reversedRatingDistribution,
      
      // 方法
      downloadResource,
      toggleFavorite,
      submitRating,
      submitComment,
      submitRatingAndComment,
      resetCommentForm,
      resetRatingForm,

      goToResource,
      getFileIcon,
      getFileIconClass,
      getCategoryTagType,
      formatFileSize,
      formatDate,
      getRatingPercentage,
      getRatingText
    }
  }
}
</script>

<style scoped>
.resource-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: calc(100vh - 160px);
}

.loading-container {
  padding: 40px 0;
}

.detail-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 资源头部 */
.resource-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 32px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-bottom: 1px solid #e4e7ed;
}

.resource-main-info {
  display: flex;
  gap: 24px;
  flex: 1;
}

.file-preview {
  position: relative;
  flex-shrink: 0;
}

.file-icon {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: white;
  position: relative;
}

.file-icon-emoji {
  font-size: 40px;
  line-height: 1;
}

.file-icon-pdf { background: linear-gradient(135deg, #ff6b6b, #ee5a24); }
.file-icon-word { background: linear-gradient(135deg, #4dabf7, #1c7ed6); }
.file-icon-ppt { background: linear-gradient(135deg, #ff8cc8, #ff6b9d); }
.file-icon-video { background: linear-gradient(135deg, #845ec2, #6c5ce7); }
.file-icon-audio { background: linear-gradient(135deg, #ffa726, #ff7043); }
.file-icon-image { background: linear-gradient(135deg, #26de81, #20bf6b); }
.file-icon-default { background: linear-gradient(135deg, #a29bfe, #6c5ce7); }

.file-type-badge {
  position: absolute;
  bottom: -8px;
  right: -8px;
  background: #409eff;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 600;
}

.resource-info {
  flex: 1;
}

.resource-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 16px 0;
  line-height: 1.3;
}

.resource-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-row {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.file-size, .upload-date {
  color: #909399;
  font-size: 14px;
}

.uploader-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.uploader-name {
  font-weight: 500;
  color: #606266;
}

.resource-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.resource-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

/* 资源描述 */
.resource-description {
  padding: 32px;
  border-bottom: 1px solid #f0f0f0;
}

.resource-description h3 {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.description-content {
  color: #606266;
  line-height: 1.6;
  font-size: 15px;
}

/* 评分区域 */
.rating-section {
  padding: 32px;
  border-bottom: 1px solid #f0f0f0;
}

.rating-section h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.rating-overview {
  display: flex;
  gap: 48px;
  margin-bottom: 32px;
}

.average-rating {
  text-align: center;
}

.rating-score {
  font-size: 48px;
  font-weight: 700;
  color: #ff9900;
  line-height: 1;
  margin-bottom: 8px;
}

.rating-stars {
  margin-bottom: 8px;
}

.rating-count {
  color: #909399;
  font-size: 14px;
}

.rating-distribution {
  flex: 1;
  max-width: 300px;
}

.rating-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.star-label {
  width: 40px;
  font-size: 14px;
  color: #606266;
}

.bar-container {
  flex: 1;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background: #ff9900;
  transition: width 0.3s ease;
}

.bar-count {
  width: 30px;
  text-align: right;
  font-size: 14px;
  color: #909399;
}

.user-rating {
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
}

.user-rating h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.rating-input {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rating-text {
  color: #ff9900;
  font-weight: 500;
}

/* 评论区域 */
.comments-section {
  padding: 32px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.comments-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.comment-item {
  display: flex;
  gap: 16px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #2c3e50;
}

.comment-rating {
  margin: 0;
}

.comment-date {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}

.comment-text {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.empty-comments {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-comments i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

/* 相关推荐 */
.related-resources {
  padding: 32px;
  background: #f8f9fa;
}

.related-resources h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.related-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.related-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.related-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.related-info {
  flex: 1;
  min-width: 0;
}

.related-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 4px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.related-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

/* 资源不存在 */
.resource-not-found {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
}

.not-found-icon {
  font-size: 80px;
  color: #ddd;
  margin-bottom: 24px;
}

.resource-not-found h3 {
  font-size: 24px;
  color: #606266;
  margin-bottom: 12px;
}

.resource-not-found p {
  color: #909399;
  margin-bottom: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .resource-detail {
    padding: 10px;
  }
  
  .resource-header {
    flex-direction: column;
    gap: 24px;
    padding: 24px 16px;
  }
  
  .resource-main-info {
    flex-direction: column;
    text-align: center;
  }
  
  .resource-actions {
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .rating-overview {
    flex-direction: column;
    gap: 24px;
  }
  
  .related-grid {
    grid-template-columns: 1fr;
  }
  
  .resource-description,
  .rating-section,
  .comments-section,
  .related-resources {
    padding: 24px 16px;
  }
}

/* 评价弹窗样式 */
.rating-dialog-content {
  padding: 16px 0;
}

.resource-info-mini {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.mini-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: linear-gradient(135deg, #409eff, #667eea);
}

.mini-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.mini-details p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.rating-input-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.rating-text {
  color: #ff9900;
  font-weight: 500;
  font-size: 14px;
}
</style> 